* ======================================
* ----------- Import gegraphy ----------
* ======================================

	use "$dta_raw\dta11\W19_0078_BOSTED.dta" , clear
	rename w19 idPers

	
* Geo in 2015
* ===========
	preserve
	keep idPers *_2015
	rename bostedskommune knr
	rename grunnkrets bsu	
	replace bsu = "" if substr(bsu, 5, 8) == "9999" // Unidentified	
	replace knr = substr(bsu,1,4) if knr == "" 		// Identify from bsu if miss.
	drop if bsu == "" 
	drop if knr == ""
	gen year = 2015
	
	tempfile geo2015
	save `geo2015'
	restore
	
	
* Geo in 2019
* ===========
	preserve
	keep idPers *_2019
	rename bostedskommune knr
	rename grunnkrets bsu
	replace bsu = "" if substr(bsu, 5, 8) == "9999" // Unidentified	
	replace knr = substr(bsu,1,4) if knr == "" 		// Identify from bsu if miss.
	drop if bsu == "" 
	drop if knr == ""
	gen year = 2019
	
	tempfile geo2019
	save `geo2019'
	restore
	
	
* Append in long format
* =====================
	
	clear
	append using `geo2015'
	append using `geo2019'

	
* Harmonize adm. changes in knr's and bsu's
* =========================================
	
	* Save a non-harmonized copy for use by certain programs
	save "$dta\ImportGeo_raw.dta",replace
	
	* BSU
	gen bsu_cngfrom = bsu
	merge m:1 bsu_cngfrom using $dta\harmonize_bsu.dta, nogen ///
		keep(master matched)
	replace bsu = bsu_cngto if bsu_harmonize == 1
	replace bsu = "" if bsu_cngto == "DROP" 		// a few non-harmonizable
	drop if bsu == ""
	drop bsu_*

	* KNR
	gen knr_cngfrom = knr
	merge m:1 knr_cngfrom using $dta\harmonize_knr.dta, nogen ///
		keep(master matched)
	replace knr = knr_cngto if knr_harmonize == 1
	drop knr_*


	sort idPers year
	save "$dta\ImportGeo.dta",replace